package com.qf.util.Filter;

import com.qf.bean.Employee;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 2020/2/3
 * 键盘敲烂，月薪过万
 * 登高必自卑，行远必自迩。
 * 不忘初心：像初学者一样拥有一颗谦虚、开放的心态。
 * 李学峰
 */
//目的就是不能在未登录的时候访问页面
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //获取session
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();//获取请求路径
        System.out.println("uri"+requestURI);
        //endsWith路径后面结尾
        if (requestURI.endsWith("login.jsp")||
                requestURI.endsWith("login")||
                requestURI.endsWith(".css")||
                requestURI.contains("/img")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
//    为什么时user呢 session.setAttribute("user", login);
            Employee user = (Employee)request.getSession().getAttribute("user");
            if (user==null){
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script>alert('请先登录');location.href='login.jsp'</script>");
            }else {
                //放行
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }
    @Override
    public void destroy() {

    }
}
